import java.io.*;

public class FileEncryptor {

    public static void main(String[] args) {
        String inputFileName = "example.txt";
        
        encryptFile(inputFileName);
        System.out.println("文件加密完成。");

        decryptFile(inputFileName);
        System.out.println("文件解密完成。");
    }

    private static void encryptFile(String fileName) {
        String tempFileName = fileName + ".tmp";
        try (InputStream in = new FileInputStream(fileName);
             OutputStream out = new FileOutputStream(tempFileName)) {
            int byteRead;
            while ((byteRead = in.read()) != -1) {
                int encryptedByte = ~byteRead;
                out.write(encryptedByte);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        new File(fileName).delete();
        new File(tempFileName).renameTo(new File(fileName));
    }

    private static void decryptFile(String fileName) {
        String tempFileName = fileName + ".tmp";
        try (InputStream in = new FileInputStream(fileName);
             OutputStream out = new FileOutputStream(tempFileName)) {
            int byteRead;
            while ((byteRead = in.read()) != -1) {
                int decryptedByte = ~byteRead;
                out.write(decryptedByte);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        new File(fileName).delete();
        new File(tempFileName).renameTo(new File(fileName));
    }
}
